package jiezi.game 
{
	import flash.events.EventDispatcher;
	import flash.display.Sprite;
    import flash.events.*;
    import flash.net.*;

	/**
	 * ...
	 * @author ...
	 */
	public class SequenceImageInfo extends EventDispatcher 
	{
		public static const EVENT_SEQINFO_READY:String = "ready";
		
		public static const ACTION_IDLE:int = 0;
		public static const ACTION_RUN:int = 1;
		public static const ACTION_MAX:int = 2;
		
		private var mSeqInfos:Object = new Object();
		private var mTobeLoadInfos:Array = new Array();
		private var mLoadingInfo:String = new String();
		private var mURLLoader:URLLoader;
		private var mCompleted:Boolean = false;

		public function SequenceImageInfo() 
		{
			mURLLoader = new URLLoader;
			mURLLoader.addEventListener(Event.COMPLETE, completeHandler)
		}
		
		public function get completed():Boolean { return mCompleted; }

		public function setSequenceID(id:int):void
		{
			mSeqInfos[ACTION_IDLE] = new Object();
			var url:String;
			for ( var i:Number = 0; i < 8; ++i ) {
				url = "data/" + id + "/0/0" + i + "/seqinfo";
				mTobeLoadInfos.push(url);
			}

			mSeqInfos[ACTION_RUN] = new Object();
			for ( i = 0; i < 16; ++i ) {
				if ( i <= 9 ) {
					url = "data/" + id + "/1/0" + i + "/seqinfo";					
				} else {
					url = "data/" + id + "/1/" + i + "/seqinfo";										
				}
				mTobeLoadInfos.push(url);
			}
			mCompleted = false;
			loadSeqImgInfos();
		}
		
		private function loadSeqImgInfos():void {
			if ( mTobeLoadInfos.length > 0 ) {
				mLoadingInfo = mTobeLoadInfos.pop();
				var request:URLRequest = new URLRequest(mLoadingInfo);
	            try {
					mURLLoader.load(request);
				} catch (error:Error) {
					trace(error);
				}
				return;
			}
			mCompleted = true;
		}
		
        private function completeHandler(event:Event):void {
            var loader:URLLoader = URLLoader(event.target);
            //trace("completeHandler: " + loader.data);
			var s:String = loader.data;
			var segs:Array = s.split(",");
			var infosegs:* = mLoadingInfo.split("/");
			
			var objDirInfo:Object = new Object();
			objDirInfo.files = new Array();
			objDirInfo.numframes = int(segs[1]);
			objDirInfo.duration = Number(segs[4]);
			for ( var i:Number = 0; i < int(segs[1]); ++i ) {
				var imgname:String = mLoadingInfo.replace("seqinfo", i + ".png");
				objDirInfo.files.push(imgname);
			}
			mSeqInfos[int(infosegs[2])][int(infosegs[3])] = objDirInfo;
			loadSeqImgInfos();
        }
		
		public function getDirInfo(action:int, dir:int):Object {
			return mSeqInfos[action][dir];
		}
	}

}